package guggaTests.tasks
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	import flexunit.framework.TestCase;
	
	import gugga.tasks.FrameWaitingTask;
	import gugga.tasks.events.TaskEvent;

	public class FrameWaitingTaskTest extends TestCase
	{
		private static const FRAME_DELAY : Number = 3;
		
		private var mPassedFramesCount : Number = 0;
		private var mFrameCounter : Sprite;
		
		public function FrameWaitingTaskTest(methodName:String=null)
		{
			super(methodName);
		}
		
		public function testFrameWaitingTaskStart() : void
		{
			var frameWaitingTask : FrameWaitingTask = new FrameWaitingTask(FRAME_DELAY);
			
			frameWaitingTask.addEventListener(TaskEvent.START, addAsync(assertFrameWaitingTaskStarted, 1000));
			
			frameWaitingTask.start();								
		}
		
		public function testFrameWaitingTaskInterrupt() : void
		{
			var frameWaitingTask : FrameWaitingTask = new FrameWaitingTask(10);
			
			frameWaitingTask.addEventListener(TaskEvent.INTERRUPTED, addAsync(assertFrameWaitingTaskInterrup, 50));
			
			frameWaitingTask.start();
			frameWaitingTask.interrupt();
		}
		
		public function testFrameWaitingTaskComplete() : void
		{
			var frameWaitingTask : FrameWaitingTask = new FrameWaitingTask(FRAME_DELAY);
			frameWaitingTask.addEventListener(TaskEvent.COMPLETED, addAsync(assertFrameWaitingTaskCompleted, 2000));
						
			mFrameCounter = new Sprite();
			mFrameCounter.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			mPassedFramesCount = 1;
			
			frameWaitingTask.start();		
		}
		
		private function assertFrameWaitingTaskStarted(aEvent : TaskEvent) : void
		{
			var frameWaitingTask : FrameWaitingTask = FrameWaitingTask(aEvent.target);
			assertTrue("FrameWaitingTask should be running", frameWaitingTask.isRunning());
		}
		
		private function assertFrameWaitingTaskInterrup(aEvent : TaskEvent) : void
		{
			var frameWaitingTask : FrameWaitingTask = FrameWaitingTask(aEvent.target);
			assertFalse("FrameWaitingTask should be interrupted (should not be running)", frameWaitingTask.isRunning());
		}
		
		private function assertFrameWaitingTaskCompleted(aEvent : TaskEvent) : void
		{
			var frameWaitingTask : FrameWaitingTask = FrameWaitingTask(aEvent.target);
			assertFalse("FrameWaitingTask should not be running", frameWaitingTask.isRunning());
						
			assertEquals("PassedFrames should be equal to " + FRAME_DELAY, 
				FRAME_DELAY, 
				mPassedFramesCount);
				
			mPassedFramesCount = 0;
			mFrameCounter = null;
			
		}
		
		private function onEnterFrame(aEvent : Event) : void
		{
			mPassedFramesCount++;
		}
	}
}